// --------------------------------------------------------------------------------------------------------------------
// <copyright file="URControlClientTcpConnection.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Microsoft.Robotics.Hardware.UniversalRobots
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    using System.Threading.Tasks;

    /// <summary>
    /// Class for connecting to URControl server with over TCP
    /// </summary>
    public class URControlClientTcpConnection : IURControlClientNetworkConnection, IDisposable
    {
        /// <summary>
        /// Tcp client to use to connect to URControl server
        /// </summary>
        private TcpClient tcpClient;

        /// <summary>
        /// Network stream for reading and writing the URControl server.
        /// </summary>
        private NetworkStream networkStream = null;

        /// <summary>
        /// Object to lock on.
        /// </summary>
        private object lockObject;

        /// <summary>
        /// Indicates whether or not instance has been disposed.
        /// </summary>
        private bool disposed;

        /// <summary>
        /// Initializes a new instance of the <see cref="URControlClientTcpConnection"/> class.
        /// </summary>
        public URControlClientTcpConnection()
        {
            this.disposed = false;
            this.tcpClient = new TcpClient();
            this.lockObject = new object();
        }

        /// <summary>
        /// Gets a value indicating whether the client is connected.
        /// </summary>
        public bool Connected
        {
            get
            {
                return this.tcpClient.Connected;
            }
        }

        /// <summary>
        /// Close connection
        /// </summary>
        public void Close()
        {
            this.Dispose();
        }

        /// <summary>
        /// Release resources.
        /// </summary>
        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Connect to the URControl server asynchronously
        /// </summary>
        /// <param name="hostname">The hostname.</param>
        /// <param name="port">Port number</param>
        /// <returns>A task.</returns>
        public Task ConnectAsync(string hostname, int port)
        {
            return this.tcpClient.ConnectAsync(hostname, port);
        }

        /// <summary>
        /// Gets the network stream for the TCP connection.
        /// </summary>
        /// <returns>A NetworkStream</returns>
        public Stream GetStream()
        {
            lock (this.lockObject)
            {
                if (this.networkStream == null)
                {
                    this.networkStream = this.tcpClient.GetStream();
                }
            }

            return this.networkStream;
        }
 
        /// <summary>
        /// Release resources.
        /// </summary>
        /// <param name="disposing">Indicates whether or not Dispose() was called.</param>
        private void Dispose(bool disposing)
        {
            // only dispose of managed resources if disposing is true
            if (disposing)
            {
                if (!this.disposed)
                {
                    this.tcpClient.Close();
                    this.tcpClient = null;

                    this.disposed = true;
                }
            }
        }
   }
}
